# -*- coding: utf-8 -*-

'''
@Software: PyCharm
@File: social_comment_emotion.py
@Author: Bryan SHEN
@E-mail: m18801919240_3@163.com
@Site:
@Time: 7月 22, 2021
@Descripton:
'''

import json
import requests
import pandas as pd
import os
import re
import regex
from loguru import logger
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
from FashionShowComment.libs.timer import time_count


class SocialCommentEmotion(object):

    def __init__(self):

        self.raw_dir = BASE_DIR + "/data/"  # 源文件夹路径
        self.res_dir = BASE_DIR + "/res/"  # 结果文件夹路径
        self.words_dir = BASE_DIR + "/libs/" #情感词语文件夹路径



    def word_list(self, file_name):
        """
        读取情感词语的文件
        """
        word_list = []
        with open(self.words_dir+ file_name + ".txt", encoding="utf-8") as f:
            for line in f.readlines():
                word_list.append(line.strip())

        return word_list

    @time_count
    def load_words(self):
        """
        加载情感词语
        """
        pos_words_file = "positive_word"
        neu_words_file = "neutral_word_comment"
        neg_words_file = "negative_word"

        self.pos_words = self.word_list(pos_words_file)
        self.neu_words = self.word_list(neu_words_file)
        self.neg_words = self.word_list(neg_words_file)



    def get_file_name(self,file_dir):
        """
        获取当前路径下所有非目录子文件
        """
        names = []
        for root, dirs, files in os.walk(file_dir):
            # print(root) #当前目录路径
            # print(dirs) #当前路径下所有子目录
            # print(files) #当前路径下所有非目录子文件
            names.append(files)
        return names

    @time_count
    def load_data(self, file_name, match_column_name):
        """
        加载数据逻辑
            file_name: 文件名
            match_column_name：需要匹配的列名，比如：text, title, content
        """
        self.data = pd.read_excel(self.raw_dir + file_name + ".xlsx")
        print(len(self.data))
        self.data[match_column_name].fillna("(中性填充)", inplace=True)  # 将空数据替换为空格 "(中性填充)"

    def emotion_judge(self, text, data_type):
        """ 情感判定逻辑 """

        #时装秀弹幕情感：正面-负面-中性，未匹配的内容走模型
        #直播卖货的情感：负面-中性-正面，未匹配的内容直接返回中性

        # url = "http://192.168.3.100:8888/sentiment/social"
        url = "http://192.168.3.108:8888/sentiment/social"

        text = str(text)

        # 将没有中文的内容判为0
        if (regex.search("[\u4e00-\u9fa5A-Za-z]+", text)) == None and ("yyds" not in text):
            return 0

        else:
            if data_type == "直播弹幕":
                # print("直播弹幕")

                # for w in self.neg_words:
                #     if regex.search(w, text) != None:
                #         return -1

                for w in self.pos_words:
                    if regex.search(w, text) != None:
                        return 1
                #
                # for w in self.neu_words:
                #     if regex.search(w, text) != None:
                #         return 0
                return "未匹配到词语"

                # data = {"text": text}
                # data_json = json.dumps(data)
                # res = requests.post(url, data=data_json)
                # feedback = json.loads(res.text)
                # emotion = feedback["details"]["emotion"]
                # return emotion


            elif data_type == "时装秀" :

                for w in self.pos_words:
                    if regex.search(w, text) != None:
                        return 1

                for w in self.neg_words:
                    if regex.search(w, text) != None:
                        return -1

                for w in self.neu_words:
                    if regex.search(w, text) != None:
                        return 0

                data = {"text": text}
                data_json = json.dumps(data)
                res = requests.post(url, data=data_json)
                feedback = json.loads(res.text)
                emotion = feedback["details"]["emotion"]
                return emotion

            else: pass


    @time_count
    def output_data(self, date, file_name):
        """ 导出文件结果 """

        output_path = self.res_dir + "/" + file_name + "_res_" + date + ".xlsx"  # 输出结果文件

        # 将url, int 等类型转换成string输出
        # self.data[["作品ID", "用户ID", "抖音ID "]] = self.data[["作品ID", "用户ID", "抖音ID"]].astype(str)

        with pd.ExcelWriter(output_path, engine='xlsxwriter', engine_kwargs={"options": {'strings_to_urls': False}}) \
                as writer:
            self.data.to_excel(writer, sheet_name='sheet1', index=False)

    @time_count
    def run_emotion(self, match_column_name, data_type):

        self.data["emotion"] = self.data[match_column_name].apply(self.emotion_judge, data_type=data_type)

    def run(self, file_name, match_column_name, date, data_type):

        """ 主程序 """

        self.load_data(file_name, match_column_name)
        self.load_words()
        self.run_emotion(match_column_name, data_type)
        self.output_data(date, file_name)